import React  from 'react'
import { connect } from 'react-redux'
import constants from 'share/constants'
import {messages} from 'share/common'
import { wrappedRowSelection } from 'components/table/table-row-selection'
import {Form, Tag, Input, Popover, Radio, Alert, Button, Modal, message, Icon} from 'antd'
import scanReceiveService from 'containers/scan-receive/scan-receive.service'
import moment from 'moment'
import AdvancedTable from 'components/advanced-table'
import selectorData from "share/selectorData";
const TextArea = Input.TextArea;
const FormItem = Form.Item;

@Form.create()
class ScanReceiveDataList extends React.Component{

  entityTypeList = {
    'all': messages('common.all')/*全部*/,
    1002: messages('expense-13.key32')/*报销单*/,
    3001: messages('expense-13.key33')/*借款单*/
  };

  notificationStatus = {
    'all': messages('common.all')/*全部*/,
    '1001': messages('expense-13.key34')/*未通知*/,
    '1002': messages('expense-13.key35')/*已通知*/
  };

  viewRange = {
    'all': messages('common.all')/*全部*/,
    '1001': messages('expense-13.key36')/*仅看本人*/,
  };

  state = {
    selectedRowKeys: [],
    loadingTipsBtn: false,
    searchForm: [{
      id: 'entityType',
      component: (
        <Radio.Group onChange={this.onChangeEntityType}>
          {Object.keys(this.entityTypeList).map(value =>
            <Radio key={value} value={value}>{this.entityTypeList[value]}</Radio>
          )}
        </Radio.Group>),
      label: messages('expense-13.key37')/*单据类型*/,
      initialValue: 'all',
      dataIndex: 'entityType',
      colSpan: 9,
      tagParser: value => this.entityTypeList[value]
    } , {
      id: 'notificationStatus',
      component: (
        <Radio.Group onChange={this.onChangeEntityType}>
          {Object.keys(this.notificationStatus).map(value =>
            <Radio key={value} value={value}>{this.notificationStatus[value]}</Radio>
          )}
        </Radio.Group>),
      label: messages('expense-13.key38')/*通知状态*/,
      initialValue: '1001',
      colSpan: 9,
      dataIndex: 'notificationStatus',
      tagParser: value => this.notificationStatus[value]
    } , {
      id: 'checkRange',
      component: (
        <Radio.Group onChange={this.onChangeEntityType}>
          {Object.keys(this.viewRange).map(value =>
            <Radio key={value} value={value}>{this.viewRange[value]}</Radio>
          )}
        </Radio.Group>),
      label: messages('expense-13.key39')/*查看范围*/,
      initialValue: '1001',
      dataIndex: 'checkRange',
      colSpan: 6,
      tagParser: value => this.viewRange[value]
    } , {
      id: 'businessCode',
      label: messages('common.document.code')/*单号*/,
      colSpan: 9,
      component: 'Input'
    }, {
      component: 'Selector',
      id: 'sendBillUserOIDs',
      dataIndex: 'sendBillUserOIDs',
      label: messages('expense-13.key40')/*寄单人姓名/工号*/,
      props: {
        placeholder: messages('expense-13.key41')/*请输入寄单人姓名/工号*/,
        type: 'user',
        selectorItem: {
          ...selectorData['user'],
          url: `/api/user/documents/review/search`,
          label: record => (`${record.employeeID}-${record.fullName}${(record.status !== 1001 ?
              (`（${record.status === 1002 ?
                  messages('expense-13.key42')/*待离职员工*/ :
                  messages('expense-13.key43')/*离职员工*/}）`
              ) :
              ''
          )}`)
        },
        searchIfKeywordIsNull: false
      },
      parser: value => ({
        sendBillUserOIDs: value ? [ value ] : null
      }),
      colSpan: 9,
      JSONObjectFormatterParams: ['fullName', 'userOID']
    } , {
      id: 'deliveryCode',
      label: messages('expense-13.key25')/*快递单号*/,
      component: 'Input',
      colSpan: 6,
    } , {
      id: 'dateRange',
      label: messages('expense-13.key8')/*寄单日期*/,
      component: 'DateRangePicker',
      colSpan: 9,
      parser: value => ({
        sendBillStartDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : null,
        sendBillEndDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : null
      })
    }]
  };

  columns = [
    {
      title: messages('common.document.code')/*单号*/, dataIndex: 'businessCode',
      render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
    }, {
      title: messages('common.document.name')/*单据名称*/,
      dataIndex: 'formName',
      render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
    }, {
      title: messages('common.submit.date')/*提交日期*/,
      dataIndex: 'lastSubmittedDate',
      width: 120,
      render: (value, record) => {
        let result = (value || record.lastSubmittedDate) ? moment(value || record.lastSubmittedDate).format('YYYY-MM-DD') : '-';
        return result;
      }
    }, {
      title: messages('expense-13.key8')/*寄单日期*/,
      dataIndex: 'sendBillDate',
      width: 120,
      render: (value, record) => {
        let result = value ? moment(value).format('YYYY-MM-DD') : moment(record.lastSubmittedDate).format('YYYY-MM-DD');
        return result;
      }
    }, {
      title: messages('expense-13.key44')/*寄单人*/,
      dataIndex: 'sendBillUserName',
      render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
    }, {
      title: messages('expense-13.key25')/*快递单号*/,
      dataIndex: 'deliveryCode',
      render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
    }, {
      title: messages('expense-13.key38')/*通知状态*/,
      dataIndex: 'notificationStatus',
      render: value => value ? (value === 1001 ? messages('expense-13.key34')/*未通知*/ : messages('expense-13.key35')/*已通知*/) : '-'
    }, {
      title: messages('common.column.status')/*状态*/,
      dataIndex: 'status',
      width: 120,
      render: (value, record) => (
        <Tag color={
          constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus', 'color') ||
          constants.getTextByValue(String(value), 'documentStatus', 'color')
        }>
          {
            constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus') ||
            constants.getTextByValue(String(value), 'documentStatus')
          }
        </Tag>
      )
    }
  ];

  service = (page, pageSize, searchParams) => {
    const { sort } = this.state;
    if (sort) {
      searchParams.sorts = {
        property: sort.split(',')[0],
        direction: sort.split(',')[1]
      };
    }
    let radioOptionGroup = ['entityType', 'notificationStatus', 'checkRange'];
    radioOptionGroup.forEach(i => searchParams[i] === 'all' && (searchParams[i] = ''));
    return scanReceiveService.getDeliveryList(page, pageSize, searchParams);
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { sort } = this.state;
    let nextSort = '';
    if(sorter.order) {
      nextSort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`;
    }
    if(nextSort !== sort) {
      this.setState({ sort: nextSort }, this.advancedTableRef.getList);
    }
  };

  onSelectChange = ( selectedRowKeys ) => this.setState({ selectedRowKeys });

  openTipsModal = () => this.setState({ showTips: true });

  closeTipsModal = () => this.setState({ showTips: false });

  handleClickInfo = () => {
    const labels = [
      messages('expense-13.key45')/*1、若企业使用了快递单寄单功能，则可在此页面查看满足下面两个条件的单据*/,
      messages('expense-13.key46')/*1）未收单单据*/,
      messages('expense-13.key47')/*2）同快递单号下存在已收单/已退单单据*/,
      messages('expense-13.key48')/*2、对此列表看到的单据可给寄单人推送交票提醒邮件*/,
    ];
    Modal.info({
      title: messages('expense-13.key49')/*了解更多*/,
      content: (
        <section>
          {labels.map(item => <p>{item}</p>)}
        </section>
      )
    });
  };

  sendDeliveryReminder = () => {
    const { selectedRowKeys } = this.state;
    this.props.form.validateFields(["tips"], (err, values) => {
      if(!err) {
        let params = {
          noticeContent: values.tips,
          billDeliveryIds: selectedRowKeys
        };
        this.setState({ loadingTipsBtn: true });
        scanReceiveService.sendDeliveryReminder(params).then(res => {
          message.success(messages('expense-13.key50')/*提醒发送成功*/);
          this.setState({ selectedRowKeys: [], loadingTipsBtn: false }, () => {
            this.closeTipsModal();
            this.advancedTableRef.getList();
          });
        }).catch(err => {
          this.setState({ loadingTipsBtn: false });
        })
      } else {
        return false;
      }
    })

  };

  render(){
    const { searchForm, selectedRowKeys, showTips, loadingTipsBtn } = this.state;
    let rowSelection = wrappedRowSelection({
      rowKey: 'billDeliveryId',
      selectedRowKeys
    }, this.onSelectChange);
    return(
      <div className="scan-receive-data-list">
        <span className="scan-receive-data-list-info" onClick={this.handleClickInfo}>
            <Icon type="bulb"/> {messages('expense-13.key49')/*了解更多*/}
        </span>
        <AdvancedTable
          index
          waterMark
          title={messages('expense-13.key31')/*交单提醒*/}
          columns={this.columns}
          searchForm={searchForm}
          service={this.service}
          rowKey="billDeliveryId"
          onRef={ref => this.advancedTableRef = ref}
          onChange={this.handleTableChange}
          tableName='delivery-reminder-list'
          expandAll
          rowSelection={rowSelection}
          notLoadWhenMount={true}
          pinnedList={['entityType', 'notificationStatus', 'checkRange']}
          footer={
            <div>
              <Button
                type='primary'
                className='delivery-reminder-btn'
                onClick={this.openTipsModal}
                disabled={!selectedRowKeys.length}
              >
                {messages('expense-13.key51')/*提醒交单*/}
              </Button>
            </div>
          }
        >
          <div className="table-header">
            <Alert
              type="info"
              showIcon
              message={messages('expense-13.key52')/*以下单据未收单，但同快递单号下存在已收单或退单单据*/}
            />
          </div>
        </AdvancedTable>
        <Modal
          visible={showTips}
          confirmLoading={loadingTipsBtn}
          onOk={() => this.sendDeliveryReminder()}
          onCancel={this.closeTipsModal}
          title={messages('expense-13.key31')/*交单提醒*/}
        >
          <Form>
            <FormItem>
            {this.props.form.getFieldDecorator('tips', {
              rules: [{
                  max: 500,
                  message: messages('expense-13.key53')/*最多输入500字*/
                }]
            })(
              <TextArea
                placeholder={messages('expense-13.key54')/*已收到您邮寄的包裹，但是此单据未收到，请注意并再次检查，谢谢！*/}
                style={{height: 120}}
              />
            )}
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
}

ScanReceiveDataList.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    request: state.cache.request,
  }
}

const wrappedScanReceiveDataList = Form.create()(ScanReceiveDataList);

export default connect(mapStateToProps)(wrappedScanReceiveDataList)


